<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/17
 * Time: 22:03
 */

namespace app\api\model;


use think\Collection;
use think\Model;

class WeTopicDetail extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * @param $data
     * @return bool
     * @throws \think\Exception
     */
    public function addTopicDetail($data)
    {
        $saveData = [
            'topic_id' => $data['topic_id'],
            'content' => $data['content'],
            'user_id' => $data['user_id']
        ];
        //todo 分词
        $data['content'] = BadWords::badWordsFilter($data['content']);
        $res = self::create($saveData);
        //评论数量+1
        WeTopic::where(['id' => $data['topic_id'], 'is_delete' => 0, 'status' => 1])->setInc('details', 1);
        if (!$res) {
            return false;
        } else {
            return $res;
        }
    }

    /**
     * @param $time
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hotId($time)
    {
        $data = self::where(['create_time' => ['>=', $time]])
            ->field('topic_id,count(*) as num')
            ->orderRaw('count(*) desc')
            ->group('topic_id')
            ->fetchSql(false)
            ->find();
        return empty($data) ? [] : $data->toArray();
    }

    public static function vote($data)
    {
        return self::where(['status' => 1, 'id' => $data['detail_id']])->setInc('likes', 1);
    }

    /**
     * 话题详情
     * @param $topic_id
     * @param string $uid
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     */
    public static function topicDetail($topic_id, $uid = '0')
    {
        $model = new self();
        $join = '';
        if ($uid) {
            $join = 'u.id = ' . $uid;
            $field = 'td.id,td.content,td.likes,td.create_time,case dl.id when dl.id then 1 else 0 end as `is_liked`';
        } else {
            $field = 'td.id,td.content,td.likes.td.create_time';
        }
        $data = $model->alias('td')
            ->join('__WE_DETAIL_LIKES__ dl', 'dl.user_id = ' . $uid . ' and dl.detail_id = td.id', 'left')
            ->where(['td.status' => 1, 'td.is_delete' => 0, 'td.topic_id' => $topic_id])
            ->field($field)
            ->order('td.create_time desc')
            ->paginate(config('sd_config.list_len'))->toArray();
        return empty($data['data']) ? [] : $data;
    }


    public static function detail($data, $uid)
    {
        $map = ['td.status' => 1, 'td.is_delete' => 0];
        $map['td.topic_id'] = $data['id'];
        $field = 'td.id,td.content,td.likes,td.create_time,u.nick_name,u.we_nick_name,u.reset_name';
        if (isset($data['start_time']) && $data['start_time']) {
            $map['td.create_time'] = ['>=', $data['start_time']];
        }
        if (isset($data['end_time']) && $data['end_time']) {
            $map['td.create_time'] = ['<', $data['end_time']];
        }
        $order = '';
        if (isset($data['order'])) {
            switch ($data['order']) {
                case 1:
                    $order = 'td.create_time desc';
                    break;
                case 2:
                    $order = 'td.create_time asc';
                    break;
                default:
                    $order = 'td.create_time desc';
            }
        }

        $model = new self();
        $data = $model->alias('td')
            ->join('__WE_USERS__ u', 'u.id = td.user_id')
            ->where($map)
            ->field($field)
            ->order($order)
            ->fetchSql(false)
//            ->select();
//        echo $data;exit;
            ->paginate(config('sd_config.list_len'))->toArray();
        if (empty($data['data'])) {
            return $data;
        } else {
            $detail_like_ids = WeDetailLikes::where(['user_id' => $uid, 'is_delete' => 0])->column('detail_id');
            $arr = array_map(function (&$item) use ($detail_like_ids) {
                if (in_array($item['id'], $detail_like_ids)) {
                    $item['is_liked'] = 1;
                    return $item;
                } else {
                    $item['is_liked'] = 0;
                    return $item;
                }
            }, $data['data']);
            $data['data'] = $arr;
            unset($arr);
        }
        return empty($data) ? [] : $data;
    }

    /**
     * 创建时间获取器
     * @param $value
     * @return false|string
     */
    public function getCreateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '0';
    }

    /**
     * 获取单条回复信息
     * @param $id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDetail($id)
    {
        $detail = self::where(['id' => $id])->find();
        return empty($detail) ? [] : $detail->toArray();
    }

    /**
     * 举报回复
     * @param $id
     * @return WeTopicDetail
     */
    public function reportDetail($id)
    {
        return self::where(['id' => $id])->update(['report' => 1]);
    }

    /**
     * 按时间倒序 获取话题id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function replyDesc()
    {
        $model = new self();
        $data = $model->alias('td')
            ->join('__WE_TOPIC__ t', 't.id = td.topic_id')
            ->join('__WE_USERS__ u', 't.user_id = u.id')
            ->where(['td.is_delete' => 0, 'td.status' => 1, 't.is_delete' => 0, 't.status' => 1])
            ->field('distinct(t.id),t.content,t.likes,t.details,t.create_time,u.nick_name,u.we_nick_name,u.reset_name,td.create_time as reply_time')
            ->order('td.create_time desc')
            ->paginate(config('list_len'))->each(function ($item){

            })->toArray();
        return empty($data['data']) ? [] : $data;


    }


    public function hotList()
    {
        //24小时内 点赞和回复总和最多
        $yesterday = strtolower('-1 day');
        $lastMonth = strtotime('last month');
        $model = new self();
        $day_list = $model->alias('td')
            ->join('__WE_TOPIC__ t', 't.id = td.topic_id')
            ->join('__WE_USERS__ u', 'u.id = t.user_id')
            ->where(['td.create_time' => ['>=', $yesterday], 'td.is_delete' => 0, 'td.status' => 1])
            ->field('distinct(td.topic_id),t.content,u.nick_name,u.reset_name,u.we_nick_name,count(*) as `total`')
            ->group('topic_id')
            ->orderRaw('count(*) desc')
            ->limit(0, config('list_len'))
            ->select();

        $day_list = array_map(function ($o) {
            $o['content'] = content_filter($o['content']);
            return $o;
        }, $day_list);
        //一个月内
        $month_list = $model->alias('td')
            ->join('__WE_TOPIC__ t', 't.id = td.topic_id')
            ->join('__WE_USERS__ u', 'u.id = t.user_id')
            ->where(['td.create_time' => ['>=', $lastMonth], 'td.is_delete' => 0, 'td.status' => 1])
            ->field('distinct(td.topic_id),t.content,u.nick_name,u.reset_name,u.we_nick_name,count(*) as `total`')
            ->group('topic_id')
            ->orderRaw('count(*) desc')
            ->limit(0, config('list_len'))
            ->select();
        $month_list = array_map(function ($m) {
            $m['content'] = content_filter($m['content']);
            return $m;
        }, $month_list);
        return ['day_list' => $day_list, 'month_list' => $month_list];
    }
}